package com.lenovo.newsapp.share;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;

/**
 * 
 * Post 请求
 */
public class AsyncPostLoader extends AsyncTask<Object, Integer, String> {
	private onPostReadyListener dataReadyListener = null;

	public AsyncPostLoader(onPostReadyListener dataReadyListener) {
		this.dataReadyListener = dataReadyListener;
	}

	@Override
	protected String doInBackground(Object... params) {
		try {
			if (params == null) {
				return null;
			}

			String url = (String) params[0];
			String jsonString = (String) params[1];
			DefaultHttpClient httpclient = new DefaultHttpClient();

			// 传递 xml 格式数据
			HttpPost httpost = new HttpPost(url);
			httpost.setHeader("Content-type", "text/xml");
			httpost.addHeader("x-li-format", "xml");

			httpclient.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
			httpclient.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
			httpclient.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
			httpclient.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);

			// Post请求
			HttpPost httppost = new HttpPost(url);
			// 设置post编码
			httppost.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
			httppost.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
			httppost.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
			httppost.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);

			// sets the post request as the resulting string
			httpost.setEntity(new StringEntity(jsonString));

			HttpResponse response = httpclient.execute(httpost);
			int statusCode = response.getStatusLine().getStatusCode();

			if (statusCode == 201) {
				String result = EntityUtils.toString(response.getEntity(), "utf-8");
				return result;
			}

		} catch (Exception e) {
		}

		return null;
	}

	@Override
	protected void onPostExecute(String result) {
		if (dataReadyListener != null) {
			dataReadyListener.onPostReady(result);
		}
	}

	/**
	 * 数据加载完毕回调接口
	 * 
	 */
	public interface onPostReadyListener {
		void onPostReady(String result);
	}
}
